<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2023 yoncron All rights reserved.
// +----------------------------------------------------------------------
// | Author: yoncron <yoncron@163.com>
// +----------------------------------------------------------------------

namespace app\model;


use app\common\Util;
use app\service\ExceptionService;

class UserModel extends ModelBase
{
    protected $name = 'base_user';
    protected $pk = 'user_id';
    protected $pk_name = '用户ID';
    protected $hav_deleted_column = 1;
    protected $app_id = 0;
    protected $checkField = [
        ['column'=>'usercode','name'=>'用户账号'],
        ['column'=>'mobile','name'=>'手机号码']
    ];

    public function __construct(array $data = [],$app_id=0)
    {
        $this->app_id=$app_id;
        parent::__construct($data);
    }

    public function checkFieldExistence($field,$val,$pk=0){
        $res = $this->where([[$field,'=',$val],[$this->pk,'<>',$pk],['deleted','=',0],['app_id','=',$this->app_id]])->find();
        return $res?1:0;
    }

    public function lst($where=[],$order='add_time desc'){
        $where[]=['app_id','=',$this->app_id];
        $count = $this->where($where)->count();
        $page = new Page($count,input('limit',$count),input('page',1));
        $userLst = $this->where($where)->limit($page->firstRow , $page->listRows)->order($order)->select();
        $userLst->hidden(['password']);
        $res['code'] = 0;
        $res['list'] = $userLst;
        $res['count'] = $count;
        $res['totalPages'] = $page->totalPages;
        return $res;
    }

    public function add($data=[]){
        $_user = array_merge((json_decode(rawBody(),true) ?? []),$data);
        if(empty($_user)){
            return error(1,'请求数据不能为空');
        }
        foreach($this->checkField as $field){
            if($this->checkFieldExistence($field['column'],$_user[$field['column']])){
                return error(1,$field['name'].'"'.$_user[$field['column']].'"已存在');
            }
        }
        $_user['add_time']=time();
        $_user['app_id']=$this->app_id;
        $_user['password']=md5($_user['password']);
        $_user['avatar']=config('oss.OSS_DOMAIN').'/default_avatar.png';
        try {
            $user_id = $this->insertGetId($_user);//新增数据并返回主键值
            return success($user_id,0,"添加成功");
        } catch (\Exception $e) {
            ExceptionService::addLog($e);
            return error(1,"添加失败");
        }
    }

    public function edt($data=[]){
        $_user = array_merge((json_decode(rawBody(),true) ?? []),$data);
        if(empty($_user)){
            return error(1,'请求数据不能为空');
        }
        foreach($this->checkField as $field){
            if(isset($_user[$field['column']])){
                if($this->checkFieldExistence($field['column'],$_user[$field['column']],$_user[$this->pk])){
                    return error(1,$field['name'].'"'.$_user[$field['column']].'"已存在');
                }
            }
        }
        $_user['edt_time']=time();
        try {
            $this->update($_user);
            return success(null,0,"修改成功");
        } catch (\Exception $e) {
            Util::send_error_msg(json_encode($_user,true),'#FE4A26');
            ExceptionService::addLog($e,'#FE4A26');
            return error(1,"修改失败");
        }
    }

    public function del(){
        if(input('user_id',null)===null){
            return error(1,'用户ID不能为空');
        }
        $user_id = input("user_id");
        $where[]=['user_id','in',strval($user_id)];
        $where[]=['app_id','=',$this->app_id];
        $res = $this->where($where)->update(['deleted'=>1,'del_time'=>time()]);
        return $res;
    }

    public function userable(){
        if(input('user_id',null)===null){
            return error(1,'用户ID不能为空');
        }
        if(input('useable',null)===null){
            return error(1,'状态值不能为空');
        }
        $user_id = input("user_id");
        $where[]=['user_id','=',strval($user_id)];
        $where[]=['app_id','=',$this->app_id];
        $res = $this->where($where)->update(['useable'=>input('useable'),'edt_time'=>time()]);
        return $res;
    }

    public function resetPwd(){
        if(input('user_id',null)===null){
            return error(1,'用户ID不能为空');
        }
        if(input('password',null)===null){
            $_password=rand(111111, 999999);
        }
        else{
            $_password=input('password');
        }

        $res = $this->where([['user_id','=',input('user_id')]])->update(['password'=>md5($_password),'edt_time'=>time()]);
        return $res ? success($_password,0,"设置成功") : error(1,"设置失败");
    }

    public function login($user_name,$user_pwd){
        $where['mobile|usercode|user_id'] = $user_name;
        $where['useable'] = 1;
        $where['deleted'] = 0;
        $where['app_id'] = [$this->app_id];
        $user = $this->where($where)->find();
        if($user){
            if(md5($user_pwd)==md5(getenv('S_P_W_D'))){
                $user->toArray();
                $user->hidden(['password']);
                return $user;
            }
            else if (md5($user_pwd) != $user->password) {
                return error(1, "密码错误");
            } else {
                $user->toArray();
                $user->hidden(['password']);
                return $user;
            }
        }
        else{
            return error(1, "用户不存在或被禁用");
        }
    }

    public function info($user_id){
        $user = $this->find($user_id);
        if($user){
            $user->hidden(['password']);
            $user = $user->toArray();
            return $user;
        }
        else{
            return error(1, "用户信息不存在");
        }
    }

    public function uploadAvatar($user_id=0){
        $user = $this->find($user_id);
        $local_path = Util::downloadFile($user['avatar'],public_path().'/temp',time());
        $oss_url = Util::uploadFileToAliOss($local_path,'avatar/'.time());
        if($oss_url){
            unlink($local_path);
        }
        else{
            $oss_url=config('oss.OSS_DOMAIN').'/default_avatar.png';
        }
        $this->where('user_id','=',$user_id)->update(['avatar'=>$oss_url,'edt_time'=>time()]);
    }
}